<template>
	<div>
		<ProTable ref="proTable" title="货品入库" :columns="columns" :requestApi="getTableList" :init-param="initParam">
			<template #searchHeader>
				<div class="mb16">
					<el-button type="primary" v-auth="'product:sync:exec:invoke'" @click="openImport"> 同步商品 </el-button>
				</div>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>

			<!-- 表格操作 -->
			<template #operation="{ row }">
				<el-button type="primary" link v-auth-all="['product:edit:invoke', 'product:details:invoke']" @click="toUpdate(row)"> 编辑 </el-button>
				<el-divider direction="vertical" />
				<el-button
					type="primary"
					link
					v-if="['AVAILABLE', 'DELISTING'].includes(row.productStatus)"
					v-auth="'product:sync:update-without-audit:invoke'"
					@click="openUpdate(row)"
				>
					免审更新
				</el-button>
				<el-divider
					direction="vertical"
					v-if="['AVAILABLE', 'DELISTING'].includes(row.productStatus)"
					v-auth="'product:sync:update-without-audit:invoke'"
				/>
				<el-button type="primary" v-if="row.productStatus === 'DELISTING'" link v-auth="'product:status:edit:invoke'" @click="onPutaway(row)">
					上架
				</el-button>
				<el-button
					type="primary"
					v-else-if="['AVAILABLE'].includes(row.productStatus)"
					link
					v-auth="'product:status:edit:invoke'"
					@click="onDelisting(row)"
				>
					下架
				</el-button>
				<el-divider direction="vertical" v-if="['AVAILABLE', 'DELISTING'].includes(row.productStatus)" v-auth="'product:status:edit:invoke'" />
				<el-button type="primary" v-if="row.productStatus !== 'AUDITING'" link v-auth="'product:sync:delete:invoke'" @click="delGood(row)">
					移除
				</el-button>
			</template>
		</ProTable>
		<SyncComp :visible="importVisible" @handleClose="closeImport"></SyncComp>
		<UpdateComp :visible="updateVisible" :row="updateRow" @handleClose="closeUpdate"></UpdateComp>
	</div>
</template>

<script setup lang="tsx" name="goodsWarehousing">
import { onMounted, ref, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import { NextLoading } from '/@/utils/loading';
import ProTable from '../../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../../components/ProTable/interface';
import { fetchSyncList, fetchDelSync, fetchPutAwaySync } from '/@/api/goods';
import SyncComp from './dialog/sync.vue';
import UpdateComp from './dialog/update.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import constant from '/@/utils/constant';

const router = useRouter();

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	searchType: 'ID',
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	return fetchSyncList(params);
};

const searchArr = [
	{
		label: '商品ID',
		value: 'ID',
	},
	{
		label: '商品名称',
		value: 'NAME',
	},
	{
		label: '商品编码',
		value: 'CODE',
	},
];

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'keywords',
		label: '商品搜索',
		isShow: false,
		search: {
			span: 2,
			xs: 1,
			sm: 1,
			md: 2,
			lg: 1,
			xl: 1,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.searchType}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => (scope.searchParam.searchType = value)}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},
	{
		prop: 'id',
		label: '商品ID',
	},
	{
		prop: 'productName',
		label: '商品名称',
		minWidth: 300,
		render: (scope) => {
			return (
				<div class="flex-center">
					<el-image class="flex-shrink" src={scope.row.productImage.split(',')[0]} style="width:50px;height:50px"></el-image>
					<div class="ml10" style="text-align:left">
						<div class="ellipsis2">{scope.row.productName}</div>
						<div>商品编码：{scope.row.productCode}</div>
					</div>
				</div>
			);
		},
	},
	{
		prop: 'productType',
		label: '商品类型',
		minWidth: 120,
		search: { el: 'select', props: { placeholder: '请选择商品类型', clearable: true, filterable: true } },
		enum: [
			{
				label: '实物',
				value: 0,
			},
			{
				label: '酒藏',
				value: 1,
			},
		],
		render(scope) {
			return scope.row.productType === 0 ? '实物' : '酒藏';
		},
	},
	{
		prop: 'productStatus',
		label: '商品状态',
		headerRender: () => {
			return <span>状态</span>;
		},
		search: { el: 'select', props: { placeholder: '选择状态', clearable: true, filterable: true } },
		enum: () => {
			return new Promise<any>((resolve) => {
				resolve({
					code: 200,
					msg: 'success',
					data: Object.keys(constant.ALIGOODSTATUS).map((v: any) => {
						return {
							label: constant.ALIGOODSTATUS[v],
							value: v,
						};
					}),
				});
			});
		},
		render: (scope: any) => {
			return scope.row.productStatus == 'AUDIT_REJECT' ? (
				<div>
					{constant.ALIGOODSTATUS[scope.row.productStatus]}
					{scope.row.reason && (
						<el-tooltip class="box-item" effect="light" content={scope.row.reason} placement="top">
							<el-icon color="red" class="mt-3 ml5" style="vertical-align: middle;">
								<WarningFilled />
							</el-icon>
						</el-tooltip>
					)}
				</div>
			) : (
				constant.ALIGOODSTATUS[scope.row.productStatus]
			);
		},
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 240, align: 'left' },
];

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.paramCode;
	});
	return target ? `输入${target?.label}搜索` : '';
});

const importVisible = ref(false);
const importRow = ref();
const updateVisible = ref(false);
const updateRow = ref();

const openImport = (row?: any) => {
	importVisible.value = true;
	importRow.value = row;
};

const closeImport = (add?: boolean) => {
	importVisible.value = false;
	importRow.value = null;
	if (add) {
		proTable.value?.getTableList();
	}
};

const toUpdate = (row?: any) => {
	router.push('/goods/list/edit/' + row.id);
};

const openUpdate = (row?: any) => {
	updateRow.value = row;
	updateVisible.value = true;
};

const closeUpdate = (add?: boolean) => {
	updateVisible.value = false;
	updateRow.value = null;
	if (add) {
		proTable.value?.getTableList();
	}
};
const delGood = async (row: any) => {
	ElMessageBox.confirm('确认移除该商品?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		const res = await fetchDelSync({ id: row.id });
		if (res.code == 200) {
			ElMessage.success('移除成功');
			proTable.value?.getTableList();
		}
	});
};
const onPutaway = async (row: any) => {
	const res = await fetchPutAwaySync({
		productId: row.id,
		productStatus: 'AVAILABLE',
	});
	if (res.code == 200) {
		ElMessage.success('上架成功');
	}
};

const onDelisting = async (row: any) => {
	const res = await fetchPutAwaySync({
		productId: row.id,
		productStatus: 'DELISTING',
	});
	if (res.code == 200) {
		ElMessage.success('下架成功');
	}
};

// 页面加载时
onMounted(() => {
	NextLoading.done();
});
</script>

<style lang="scss">
.demo-tabs {
	.el-tabs__header {
		margin-bottom: 0;
	}
}
</style>
